package laf.behaviours;

import jade.core.Agent;
import jade.core.behaviours.SimpleBehaviour;
import laf.time.TimeManager;

public abstract class TickerBehaviour extends SimpleBehaviour {
	
	private static final long serialVersionUID = 3402194162712949900L;
	private long period;
	private int priority;
	private TimeManager tm;
	private boolean done;
	private boolean unblocked = true;
	
	public TickerBehaviour(Agent agent, long period, int priority) {
		super(agent);
		if (period <= 0) {
			throw new IllegalArgumentException("Period must be greater than 0");
		}
		this.period = period;
		if (priority < TimeManager.MIN_PRIORITY || priority > TimeManager.MAX_PRIORITY) {
			throw new IllegalArgumentException("Priority must be between " + TimeManager.MIN_PRIORITY + " and " + TimeManager.MAX_PRIORITY + " inclusivly");
		}
		this.priority = priority;
		tm = TimeManager.getInstance();
	}

	@Override
	public void action() {
		while (!done && unblocked) {
			onTick();
			unblocked = false;
			new Thread() { 
				public void run() {
					tm.waitTicks(period, priority);
					unblock();
				}
			}.start();
		}
	}

	@Override
	public boolean done() {
		return done;
	}
	
	private void unblock() {
		unblocked = true;
		restart();
	}
	
	public void stop() {
		done = true;
	}
	
	protected abstract void onTick();
}
